import {
  Controller,
  Get,
  Post,
  Body,
  Inject,
  Query,
  UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';

import { AuthService } from './auth.service';

import { AuthSendCodeDto } from './dto/send-code.dto';
import { AuthRegisterDto } from './dto/register-auth.dto';
import { AuthLoginDto } from './dto/login-auth.dto';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Inject(JwtService)
  private jwtService: JwtService;
  @Inject(ConfigService)
  private configService: ConfigService;

  @Post('register')
  async register(@Body() registerUser: AuthRegisterDto) {
    return this.authService.register(registerUser);
  }

  @Post('login')
  async login(@Body() authLogin: AuthLoginDto) {
    const result = await this.authService.login(authLogin);
    result.accessToken = await this.jwtService.sign(
      {
        userId: result.userInfo.id,
        username: result.userInfo.username,
        roles: result.userInfo.roles,
        permissions: result.userInfo.permissions,
      },
      {
        expiresIn:
          this.configService.get('JWT_ACCESS_TOKEN_EXPIRES_TIME') || '30m',
      },
    );

    result.refreshToken = await this.jwtService.sign(
      {
        userId: result.userInfo.id,
      },
      {
        expiresIn:
          this.configService.get('JWT_REFRESH_TOKEN_EXPIRES_TIME') || '7d',
      },
    );

    return {
      code: 200,
      msg: '登录成功',
      data: {
        userInfo: result.userInfo,
        accessToken: result.accessToken,
        refreshToken: result.refreshToken,
      },
    };
  }

  @Get('refresh-token')
  async refreshToken() {}

  @Post('send-code')
  async sendVerificationCode(@Body() sendCodeDto: AuthSendCodeDto) {
    return this.authService.sendEmail(sendCodeDto.email);
  }

  @Get('refresh')
  async refresh(@Query('refreshToken') refreshToken: string) {
    try {
      const data = this.jwtService.verify(refreshToken);

      const user = await this.authService.findUserById(data.userId);

      const access_token = this.jwtService.sign(
        {
          userId: user.id,
          username: user.username,
          roles: user.roles,
          permissions: user.permissions,
        },
        {
          expiresIn:
            this.configService.get('JWT_ACCESS_TOKEN_EXPIRES_TIME') || '30m',
        },
      );
      const refresh_token = this.jwtService.sign(
        {
          userId: user.id,
        },
        {
          expiresIn:
            this.configService.get('JWT_REFRESH_TOKEN_EXPIRES_TIME') || '7d',
        },
      );
      return { access_token, refresh_token };
    } catch (error) {
      throw new UnauthorizedException('token 已失效，请重新登录');
    }
  }
}
